/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.castor.castor;

import cn.easyplatform.castor.Castor;
import cn.easyplatform.castor.FailToCastObjectException;

import java.util.HashMap;
import java.util.Map;

import static java.lang.String.format;

@SuppressWarnings({ "rawtypes" })
public class String2Class extends Castor<String, Class> {

	public String2Class() {
		fromClass = String.class;
		toClass = Class.class;
	}

	public static final Map<String, Class<?>> map = new HashMap<String, Class<?>>();
	static {
		map.put("long", long.class);
		map.put("int", int.class);
		map.put("short", short.class);
		map.put("byte", byte.class);
		map.put("float", float.class);
		map.put("double", double.class);
		map.put("char", char.class);
		map.put("boolean", boolean.class);
	}

	@Override
	public Class<?> cast(String src, Class toType, String... args) {
		if (null == src)
			return null;
		Class<?> c = map.get(src);
		if (null != c)
			return c;
		try {
			return Class.forName(src);
		} catch (ClassNotFoundException e) {
			throw new FailToCastObjectException(format(
					"String '%s' can not cast to Class<?>!", src));
		}
	}

}
